<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\AdminUsers;
use App\Admin\Models\Store;
use App\Admin\Models\StoreInnerSales;
use App\Admin\Models\Product;
use App\Admin\Models\Common;
use App\Admin\Extensions\AggreeConsume;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\MessageBag;
use Illuminate\Http\Request;


class InnerSalesController extends Controller
{
	use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('内销商品')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('产品')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        session(['inner_sales_id' => $id]);
        return $content
            ->header('产品')
            ->description('编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        session(['inner_sales_id' => 0]);
        return $content
            ->header('产品')
            ->description('新增')
            ->body($this->form());
    }

//  public function update(Request $request, $id)
//  {
//
//  }

//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {
//
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StoreInnerSales());
        $grid->sisId('ID');
        $grid->sgName('产品名称');
        $grid->goodsNum('产品数量');
//        $grid->name('取货店员');
		$grid->remark('内销原因');
        $grid->createUser('操作人员');
        $grid->status('申请状态')->display(function ($key){
            $status = ['0' => '申请中', '2' => '已拒绝', '10' => '已同意'];
            return $status[$key];
        });
        $grid->createTime('操作时间');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		if (Admin::user()->isRole('manager')){
			// 添加批量提交按钮
			$grid->tools(function (Grid\Tools $tools) {

				$operator = Admin::user()->name;
    			$sId = Admin::user()->sId;

			    $tools->append('<div id="btnAggree" class="btn btn-sm btn-warning form-history-bac" style="float: right;margin-left: 25px;">审核通过</div>');

				////////////////////////////
				$url = route('aggreeConsume');
				$hideScript = <<<EOT

var clikceAggree = false;
$("#btnAggree").click(function(){
    if (clikceAggree){
        return false;
    }
    clikceAggree = true;
	var sisIds = "";
	for(var i=0;i<$(".grid-row-checkbox").length;i++){
		if($(".grid-row-checkbox")[i].checked){
			sisIds += "," + $(".grid-row-checkbox")[i].dataset.id;
		}
	}
	if (sisIds == ""){
		toastr.warning('请勾选要同意的申请');
		return;
	}
    
    $("#btnAggree").html('请求中...');
    
	sisIds = sisIds.substring(1);

	$.ajax({
	  type: 'POST',
	  url: '{$url}',
	  data: {
	  	sId: '{$sId}',
	  	sisIds: sisIds,
	  	operator: '{$operator}'
	  },
	  dataType: 'json',
	  success: function(data){
	  	if (data.code == 1){
	  		window.location.reload();
	  	}else{
	  		toastr.warning(data.msg);
	  	}
	  }
	});
});

EOT;
				Admin::script($hideScript);
				///////////////////////////
			});
		}else{
			// 禁用行选择checkbox
			$grid->disableRowSelector();
		}


//		$grid->tools(function ($tools) {
//		    $tools->batch(function ($batch) {
//		    	$batch->disableDelete();
//		        $batch->add('内销通过', new AggreeConsume());
//		    });
//		});


		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
		    $actions->disableView();
		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
            $filter->like('sgName', '产品名称');
//		    $filter->column(1/2, function ($filter) {
//
//		    	$filter->like('sgName', '产品名称');
//
//			});

		});

		// 默认展开筛选框
//		$grid->expandFilter();

		// 禁用导出
		$grid->disableExport();

		// 禁用查询过滤器
		$grid->disableFilter();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Product = new Product();
        $show = new Show($Product->findOrFail($id));

        $show->sgId('ID');
        $show->sgName('产品名称');
        $show->sgLogo('产品图片');
        $show->sgDesc('产品描述');
        $show->sgPrice('产品单价');
        $show->dpId('分销规则');
		$Common = new Common();
		$dpSelect = $Common->getPreceptSelect();
        $show->dpId('分销规则')->using($dpSelect);
        $show->sgNum('库存');
        $show->sgWarningNum('库存警报数量');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');
		$show->sgIsChaffer('议价')->using(['1' => '是','0' => '否'])->value('1');
		$show->panel()
			->tools(function ($tools) {
//				$tools->disableEdit();
//				$tools->disableList();
				$tools->disableDelete();
		});;
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id = 0)
    {
//        var_dump(Admin::user()->name);exit;


        return Admin::Form(StoreInnerSales::class, function (Form $form) use($id) {
//			echo Admin::user()->auCode;exit;
			$form->hidden('sisId');
            $form->hidden('auCode')->default(Admin::user()->auCode);
            $form->hidden('sId')->default(Admin::user()->sId);
			$form->select('goodsId', '产品名称')
                ->options(Store::all()->where('sId', Admin::user()->sId)->pluck('sgName', 'sgId'))
                ->rules('required');

			if($id){
                $form->number('goodsNum', '产品数量')->attribute(['readonly'=>'readonly']);
           }else{
                $form->number('goodsNum', '产品数量')->value(1);
            }

//			$form->select('userName', '拿货人')
//                ->options(AdminUsers::all()->where('id', '>', 1)->pluck('name', 'id'));
			$form->text('createUser', '操作人')->value(Admin::user()->name)->attribute(['readonly'=>'readonly']);
            // 如果管理员显示状态
			if(Admin::user()->isRole('manager') && $id) {
			    $rst = StoreInnerSales::all()->where('sisId', $id)->first();

			    if($rst['status'] == 10){
//                    $form->select('status', '状态')->options(['0' => '申请中', '2' => '已拒绝', '10' => '已同意'])
//                    ->attribute(['disabled'=>'disabled']);
                    $form->display('status', '状态')->with(function ($value) {
                        $status = ['0' => '申请中', '2' => '已拒绝', '10' => '已同意'];
                        return $status[$value];
                    });

                }else{
                    $form->select('status', '状态')->options(['0' => '申请中', '2' => '已拒绝', '10' => '已同意']);
                }
            }
            $form->textarea('remark', '备注');
			$form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

            $form->saving(function (Form $form) {
                $rst = Store::all()->where('sgId', $form->goodsId)->first();
                if($rst){
                    if($rst['sgNum'] < $form->goodsNum){
                        $error = new MessageBag([
                            'title'   => '提示',
                            'message' => '库存不足，不能加入内销',
                        ]);

                        return back()->with(compact('error'))->withInput();
                    }
                }

            });

            $form->saved(function (Form $form) {
                // 同意就减库存
                if($form->status == 10){
                	$sId = Admin::user()->sId;
                	$auId = $form->auCode;
                	$sgId = $form->goodsId;
                	$sgoSaleNum = $form->goodsNum;
                	$sgoSalePrice = 0;
                	$sgoMemo = '内消';
                	$createUser = Admin::user()->name;
                	$muId = '';
                	$sgoPayWay = '内消';

                	$result = $this->common->sellGoods($sId, $auId, $sgId, $sgoSaleNum,$sgoSalePrice,
								$sgoMemo, $createUser, $muId, $sgoPayWay);

                    DB::table('store_inner_sales')->where('sisId', $form->sisId)->update(['status' => 10, 'updateUser' => $createUser]);
                } elseif ($form->status == 2){
                	DB::table('store_inner_sales')->where('sisId', $form->sisId)->update(['status' => 2, 'updateUser' => $createUser]);
                }
            });

			$form->footer(function ($footer) use ($id){
			    if($id) {
                    $rst = StoreInnerSales::all()->where('sisId', $id)->first();

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
                // 如果同意了就不能修改了
//			    // 去掉`提交`按钮
                    if ($rst['status'] == 10) {
                        $footer->disableSubmit();
                    }
                }
			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }

}
